<!DOCTYPE html>
<html lang="ch-CN">
<head>
    <meta charset="UTF-8">
    <title>div-上下左右移动</title>
</head>
<style>
    body {
        width: 100vw;
        height: 100vh;
        background-color: wheat;
        font-size: 30px;
        /*文本透明*/
        /*text-decoration: none;*/
        font-family: "华文楷体";
        display: flex;
        justify-content: center;
        align-items: center;
    }

    #box1 {
        background-color: grey;
        width: 200px;
        height: 200px;
    }
</style>
<body>
<div id="box1"></div>
</body>
<script>
    function key(a) {
        let box = document.getElementById(a)
        // 将box设置为相对定位
        box.style.position = "relative"
        // box.style.left和top的值不设置为0默认就没有 box.style.left值的类型是字符型后面需要用parseInt取整
        box.style.left = "0px"
        box.style.top = "0px"
        document.onkeydown = function (event) {
            let num=event.keyCode
            move(num,box)
        }
    }
    // box移动函数
    function move(num,box){
        switch (num) {
            case 37:
                box.style.left = parseInt(box.style.left) - 10 + "px"
                break;
            case 38:
                box.style.top = parseInt(box.style.top) - 10 + "px"
                break
            case 39:
                box.style.left = parseInt(box.style.left) + 10 + "px"
                break;
            case 40:
                box.style.top = parseInt(box.style.top) + 10 + "px"
                break
        }
        // if (event.keyCode === 37) {
        //     box.style.left = parseInt(box.style.left) - 10 + "px"
        // } else if (event.keyCode === 38) {
        //     box.style.top = parseInt(box.style.top) - 10 + "px"
        // } else if (event.keyCode === 39) {
        //     box.style.left = parseInt(box.style.left) + 10 + "px"
        // } else if (event.keyCode === 40) {
        //     box.style.top = parseInt(box.style.top) + 10 + "px"
        // }

    }
    // 函数调用
    key("box1")
</script>
</html>